package de.bastian.hinterleitner;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import de.bastian.hinterleitner.tools.Helper;
import de.hijacksoft.wyc.R;

public class SmallWidget extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		for (int widgetId : appWidgetIds) {
			RemoteViews remoteViews = new RemoteViews(context
					.getApplicationContext().getPackageName(),
					R.layout.widget_small_layout);
			Log.d("SERVICE", "updating small widget");

			remoteViews = configureRemoteViews(context, remoteViews);

			// Register an add onClickListener
			Intent addIntent = new Intent(context.getApplicationContext(),
					Main.class);
			addIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

			PendingIntent pendingIntent = PendingIntent.getActivity(context,
					widgetId, addIntent, Intent.FLAG_ACTIVITY_CLEAR_TASK);

			remoteViews.setOnClickPendingIntent(R.id.widget_add, pendingIntent);
			remoteViews.setOnClickPendingIntent(R.id.widget_txt_red,
					pendingIntent);
			remoteViews.setOnClickPendingIntent(R.id.widget_txt_green,
					pendingIntent);

			appWidgetManager.updateAppWidget(widgetId, remoteViews);
		}
	}

	public static RemoteViews configureRemoteViews(Context context,
			RemoteViews remoteViews) {
		
		SharedPreferences sp = context.getSharedPreferences("values", context.MODE_PRIVATE);
		
		// update total
		int total = (int) Helper.getThisMonthsTotal(context);
		double rest = sp.getFloat("budget", 200)+total;
		String amount = Helper.shorten(total);
		
		String left =Helper.shorten(rest);
		
		remoteViews.setTextViewText(R.id.widget_txt_red, amount);
		remoteViews.setTextViewText(R.id.widget_txt_green,amount);
		if(sp.getFloat("budget", 200)==0){
			remoteViews.setTextViewText(R.id.widget_txt_left, "");
		}else{
			remoteViews.setTextViewText(R.id.widget_txt_left, left+" "+context.getString(R.string.left));
		}

		if (total < 0) {
			remoteViews.setViewVisibility(R.id.widget_txt_red, View.VISIBLE);
			remoteViews.setViewVisibility(R.id.widget_txt_green, View.GONE);
		} else {
			remoteViews.setViewVisibility(R.id.widget_txt_red, View.GONE);
			remoteViews.setViewVisibility(R.id.widget_txt_green, View.VISIBLE);
		}
		return remoteViews;
	}

}